<!-- 重点参数：renderOptions.pointStyle.content -->
<!doctype html>
<html lang="zh-CN">

<head>
    <!-- 原始地址：//webapi.amap.com/ui/1.0/ui/misc/PointSimplifier/examples/img-content.html -->
    <!--<base href="//webapi.amap.com/ui/1.0/ui/misc/PointSimplifier/examples/" />-->
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <script src="{$protocol}cache.amap.com/lbs/static/es5.min.js"></script>
    <script type="text/javascript" src='{$protocol}webapi.amap.com/maps?v=1.4.8&key={$gd_key}'></script>
    <script type="text/javascript" src="{$protocol}cache.amap.com/lbs/static/addToolbar.js"></script>
    <title>图片内容</title>
    <style>
        html,
        body,
        #container {
            width: 100%;
            height: 100%;
            margin: 0px;
        }

        #loadingTip {
            position: absolute;
            z-index: 9999;
            top: 0;
            right: 0;
            padding: 3px 10px;
            background: red;
            color: #fff;
            font-size: 13px;
        }
        .info {
            border: solid 1px silver;
        }
        div.info-top {
            position: relative;
            background: none repeat scroll 0 0 #F9F9F9;
            border-bottom: 1px solid #CCC;
            border-radius: 5px 5px 0 0;
        }
        div.info-top div {
            display: inline-block;
            color: #333333;
            font-size: 14px;
            font-weight: bold;
            line-height: 31px;
            padding: 0 10px;
        }
        div.info-top img {
            position: absolute;
            top: 10px;
            right: 10px;
            transition-duration: 0.25s;
        }
        div.info-top img:hover {
            box-shadow: 0px 0px 5px #000;
        }
        div.info-middle {
            font-size: 12px;
            padding: 6px;
            line-height: 20px;
        }
        div.info-bottom {
            height: 0px;
            width: 100%;
            clear: both;
            text-align: center;
        }
        div.info-bottom img {
            position: relative;
            z-index: 104;
        }
        span {
            margin-left: 5px;
            font-size: 11px;
        }
        .info-middle img {
            float: left;
            margin-right: 6px;
        }
    </style>
</head>

<body>
<div id="container"></div>
<!-- UI组件库 1.0 -->
<script src="{$protocol}webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
<script src="__PUBLIC__/js/jquery.js"></script>
<script type="text/javascript">
    //创建地图
    var timeVal,pointSimplifierIns,geolocation,bounds,code;
    var init = 0,cycle = 15000;
    var map = new AMap.Map('container');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: false,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:false,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            // noIpLocate:3
        });
        map.addControl(geolocation);
        // tip('定位中……');
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });

    //解析定位结果
    function onComplete(data) {
        geolocation.getCityInfo(function (status,result) {
            var code_tmp = new Object();
            if(status==='complete'){
                code_tmp.key = 'city';
                code_tmp.value = result.adcode;
            }else{
                code_tmp.key = 'ad';
                code_tmp.value = data.addressComponent.adcode;
            }
            code = JSON.stringify(code_tmp);
            initMarker('init');
        });
    }

    //解析定位错误信息
    function onError(data) {
        bound();
        initMarker('moveend');
        /*setTimeout(function () {
            geolocation.getCurrentPosition();
        },cycle);*/
    }

    //构建自定义信息窗体
    function createInfoWindow(title, content) {
        var info = document.createElement("div");
        info.className = "info";

        //可以通过下面的方式修改自定义窗体的宽高
        //info.style.width = "400px";
        // 定义顶部标题
        var top = document.createElement("div");
        var titleD = document.createElement("div");
        var closeX = document.createElement("img");
        top.className = "info-top";
        titleD.innerHTML = title;
        closeX.src = "{$protocol}webapi.amap.com/images/close2.gif";
        closeX.onclick = closeInfoWindow;

        top.appendChild(titleD);
        top.appendChild(closeX);
        info.appendChild(top);

        // 定义中部内容
        var middle = document.createElement("div");
        middle.className = "info-middle";
        middle.style.backgroundColor = 'white';
        middle.innerHTML = content;
        info.appendChild(middle);

        // 定义底部内容
        var bottom = document.createElement("div");
        bottom.className = "info-bottom";
        bottom.style.position = 'relative';
        bottom.style.top = '0px';
        bottom.style.margin = '0 auto';
        var sharp = document.createElement("img");
        sharp.src = "{$protocol}webapi.amap.com/images/sharp.png";
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
    }

    //关闭信息窗体
    function closeInfoWindow() {
        map.clearInfoWindow();
    }

    map.on('movestart',function () {
        if(init>0){
            clearInterval(timeVal);
        }
    });

    map.on('moveend',function (){
        if(init>0){
            tip('加载数据，请稍候...');
            timeVal = setInterval(createPoints,cycle,'moveend');
        }
        bound();
        init++;
    });

    //获取视图中的对角点
    function bound() {
        var bound = map.getBounds();
        var northeast = new Array();
        var southwest = new Array();
        var temp = new Array();
        northeast[0] = bound.northeast.lng;
        northeast[1] = bound.northeast.lat;
        southwest[0] = bound.southwest.lng;
        southwest[1] = bound.southwest.lat;
        temp[0] = northeast;
        temp[1] = southwest;
        bounds = JSON.stringify(temp);
    }

    //加载海量点插件
    function initMarker(type) {
        AMapUI.load(['ui/misc/PointSimplifier', 'lib/$'], function(PointSimplifier, $) {
            if (!PointSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！');
                return;
            }
            tip('加载数据，请稍候...');
            //启动页面
            initPage(PointSimplifier,type);
        });
    }

    function tip(mes) {
        $('<div id="loadingTip">'+mes+'</div>').appendTo(document.body);
    }

    function initPage(PointSimplifier,type) {
        var groupStyleMap;
        //创建组件实例
        pointSimplifierIns = new PointSimplifier({
            zIndex: 300,
            map: map,
            autoSetFitView: false,
            getPosition: function(item) {
                if (!item) {
                    return null;
                }
                return item.location;
            },
            getHoverTitle: function(dataItem, idx) {
                /*var str = "车牌号：  " + dataItem.car_plate + "<br>";
                str += "司机id：  " + dataItem.driver_id + "<br>";
                str += "认证类型：  " + dataItem.type + "<br>";
                str += "当前坐标：  " + dataItem.location[0] +','+ dataItem.location[1] + "<br>";
                str += "订单号：  " + dataItem.order_sn;*/
                return null;
            },
            //使用GroupStyleRender
            renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,
            renderOptions: {
                //点的样式
                pointStyle: {
                    //绘制点占据的矩形区域
                   /*content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$protocol}a.amap.com/lbs/static/webapi_demo/taxi.png',
                        function onload() {
                            pointSimplifierIns.renderLater();
                        },
                        function onerror(e) {
                            alert('图片加载失败！');
                        }),
                     //定位点为底部中心
                    offset: ['-50%', '-50%'],
                        */
                    //宽度
                    width: 16,
                    //高度
                    height: 16,
                    fillStyle: null,//'#A2D0FA',
                    strokeStyle: null
                },
                getGroupId: function(item, idx) {
                    var id;
                    switch (item.type) {
                        case '出租车':
                            id = 0;
                            break;
                        case '城内专车':
                            id = 1;
                            break;
                        default:
                            id = 2;
                            break;
                    }
                    return id;
                },
                groupStyleOptions: function(gid) {

                    return groupStyleMap[gid];
                }
            }
        });
        function onIconLoad() {
            pointSimplifierIns.renderLater();
        }
        function onIconError(e) {
            console.log(e);
            // alert('图片加载失败！');
        }
        groupStyleMap = {
            '0': {
                pointStyle: {
                    //绘制点占据的矩形区域
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$protocol}a.amap.com/lbs/static/webapi_demo/taxi.png', onIconLoad, onIconError),
                    //宽度
                    width: 16,
                    //高度
                    height: 16,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
            '1': {
                pointStyle: {
                    //绘制点占据的矩形区域
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$protocol}a.amap.com/lbs/static/webapi_demo/bike.png', onIconLoad, onIconError),
                    //宽度
                    width: 16,
                    //高度
                    height: 16,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
            '2': {
                pointStyle: {
                    //绘制点占据的矩形区域
                    content: PointSimplifier.Render.Canvas.getImageContent(
                        '{$protocol}a.amap.com/lbs/static/webapi_demo/truck.png', onIconLoad, onIconError),
                    //宽度
                    width: 16,
                    //高度
                    height: 16,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null,
                    strokeStyle: null
                }
            },
        };
        timeVal = setInterval(createPoints,cycle,type);
        pointSimplifierIns.on('pointClick', function(e, record) {
            var data = record.data,url;
            //实例化信息窗体
            var title = '司机<span style="font-size:11px;color:#F00;">'+data.driver_name+'</span> 信息',
                content = [];
            content.push("当前坐标："+data.location[0] +','+ data.location[1]);
            content.push("车牌号："+data.car_plate);
            content.push("车辆品牌："+data.car_brand);
            content.push("车辆型号："+data.car_model);
            content.push("车辆颜色："+data.color);
            content.push("认证类型："+data.type);
            switch (data.type){
                case '城际拼车':
                    url = "{$url_inter}"+"?driver_id="+data.driver_id;
                    break;
                default:
                    url = "{$url_inner}"+"?driver_id="+data.driver_id;
                    break;
            }
            content.push("<a href='"+url+"'>详细信息</a>");
            var infoWindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                content: createInfoWindow(title, content.join("<br/>")),
                offset: new AMap.Pixel(14, -28)
            });
            infoWindow.open(map,new AMap.LngLat(data.location[0],data.location[1]));
        });
    }

    //设置数据源，data需要是一个数组
    function createPoints(type) {
        $.post('/index/other/getLocal',
            {
                type : type,
                code : code,
                bounds : bounds
            }
        ,function(csv) {
            $('#loadingTip').remove();
            if(csv.status){
                var data = csv.data;
                pointSimplifierIns.setData(data);
            }else{
                tip(csv.msg);
            }
        });
    }
</script>
</body>

</html>